#include "main_interface.h"
#include "ui_main_interface.h"

#include "global_variant.h"

#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QBitmap>
#include <QPainter>
#include <QMovie>
#include <QMouseEvent>
#include <QToolTip>
#include <QComboBox>

QString g_mainterfaceConnectDatabaseName_1 = "mainInterface_mysql_connection_1";//信息总库
QString g_mainterfaceConnectDatabaseName_2 = "mainInterface_mysql_connection_2";//车辆信息库
QString g_mainterfaceConnectDatabaseName_3 = "mainInterface_mysql_connection_3";//成绩信息库

QHash<int, QPair<QString, int>> g_Client2Hash;
QHash<QPair<QString, int>, int> g_Hash2Client;

bool g_isExecuteEquipmentExam = false;
bool g_isRouteEquipmentExam = false;
bool g_isTampingHomeworkEquipmentExam = false;

bool g_isExecuteEquipmentExamTimeout = false;
bool g_isRouteEquipmentExamTimeout = false;
bool g_isTampingHomeworkEquipmentExamTimeout = false;

bool g_insertExecuteEquipmentExamTimeoutRecord = false;
bool g_insertRouteEquipmentExamTimeoutRecord = false;
bool g_insertTampingHomeworkEquipmentExamTimeoutRecord = false;

//运行前检查的考试表创建时间戳
QString g_examineExamTableName = "";
qint64 g_examineExamCreatetimestamp = 0;

//线路驾驶的考试表
QString g_routeExamTableName = "";
qint64 g_routeExamCreatetimestamp = 0;

//捣固作业的考试表
QString g_tampingHomeworkTableName = "";
qint64 g_tampingHomeworkCreatetimestamp = 0;


QHash<QString, int> g1_examSubstepNumberRecord;
int g1_executeIndex;

//线路驾驶
extern QHash<QString, int> g2_examSubstepNumberRecord;
int g2_executeIndex;

//捣固作业
extern QHash<QString, int> g3_examSubstepNumberRecord;
extern int g3_executeIndex;

////语音
//环车检查设别的语音
QString g_voiceRecord1 = "";
//线路驾驶设别的语音
QString g_voiceRecord2 = "";
//捣固作业的语音
QString g_voiceRecord3 = "";


MainInterface::MainInterface(QWidget *parent)
    : QMainWindow(parent, Qt::FramelessWindowHint)
    , ui(new Ui::MainInterface)
{
    ui->setupUi(this);

    //this->setWindowFlags(this->windowFlags() &~ (Qt::WindowMinMaxButtonsHint));
    //棱角圆滑
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.setPen(Qt::transparent);//表示RGBA值为(0,0,0,0)的透明色。
    p.setRenderHint(QPainter::Antialiasing); // 反锯齿;
    p.drawRoundedRect(bmp.rect(), 20, 20);
    setMask(bmp);

    //关闭按钮
    ui->closePushButton->setStyleSheet("QPushButton{border-image: url(:/Image/closeButton.png)}");

    //关闭按钮
    connect(ui->closePushButton, &QPushButton::clicked,
            this, [&](){
                QString tipText = "";
                if(m_examineExamEquipmentLoginStatus == true){
                    tipText += "运行前检查端";
                }

                if(m_routeExamEquipmentLoginStatus == true){
                    if(tipText.size() == 0){
                        tipText += "驾驶端";
                    }else{
                         tipText += "或驾驶端";
                    }
                }

                if(m_tampingHomeworkEquipmentLoginStatus == true){
                    if(m_routeExamEquipmentLoginStatus == true
                        || m_examineExamEquipmentLoginStatus == true){
                         tipText += "或捣固作业端";
                    }else{
                        tipText += "驾驶端";
                    }
                }

                tipText += QString("正在有学员登录，请退出登陆后，再操作，谢谢！");



                if(m_examineExamEquipmentLoginStatus == true
                || m_routeExamEquipmentLoginStatus == true
                || m_tampingHomeworkEquipmentLoginStatus == true){
                    auto button = QMessageBox::warning(this,  tr("信息提示"),
                                                      tipText,  QString("确定"),  0);

                    if (button == 0){//退出程序

                    }
                }else{
                    exit(0);
                }
            });

    //初始化界面风格
    initializeMainInterfaceSetStyleSheet();

    initializeExamineExamManagePageSetStyleSheet();

    initializeRouteExamManagePageSetStyleSheet();

    initializeTampingHomeworkExamManagePageSetStyleSheet();

    //初始化界面功能
    initializeExamineExamManagePageFunction();

    //初始化表格字段映射
    initializeTableFieldHash();

    //主界面切换
    ui->equipmentManagePageLabel_1->installEventFilter(this);
    ui->equipmentManagePageLabel_2->installEventFilter(this);
    ui->equipmentManagePageLabel_3->installEventFilter(this);

    ui->examineExamManagePageLabel_0->installEventFilter(this);
    ui->examineExamManagePageLabel_2->installEventFilter(this);
    ui->examineExamManagePageLabel_3->installEventFilter(this);

    ui->routeExamManagePageLabel_0->installEventFilter(this);
    ui->routeExamManagePageLabel_1->installEventFilter(this);
    ui->routeExamManagePageLabel_3->installEventFilter(this);

    ui->tampingHomeworkExamManagePageLabel_0->installEventFilter(this);
    ui->tampingHomeworkExamManagePageLabel_1->installEventFilter(this);
    ui->tampingHomeworkExamManagePageLabel_2->installEventFilter(this);

    //功能选择登录界面

    //练习模式
    ui->tampingHomeworkTrainingLabel->installEventFilter(this);
    ui->examineTrainingLabel->installEventFilter(this);
    ui->routeTrainingLabel->installEventFilter(this);

    //考试模式
    ui->examineExamLabel->installEventFilter(this);

    //结束按钮
    ui->endExamineEquipmentLabel->installEventFilter(this);
    // ui->endRouteEquipmentLabel->installEventFilter(this);
    // ui->endTampingHomeworkEquipmentLabel->installEventFilter(this);

    //旋转等待界面
    m_waitProcessBar = new WaitProcessBar(this);

    //初始化监听线程
    //initializeNetworkStatusThread();

    //初始化服务器
   initializeTcpServer();

    //开启tcp服务
   startTcpServer();

}

MainInterface::~MainInterface()
{
    //退出网络监控的线程
    m_dealNetworkStatusThread.quit();//停止事件循环
    m_dealNetworkStatusThread.wait();//阻塞知道线程结束

    //关闭全部套接字
    emit closeAllSocket();

    //关闭数据库1(总数据库)
    QSqlDatabase db1 = QSqlDatabase::database(g_mainterfaceConnectDatabaseName_1);
    db1.close();
    db1 = QSqlDatabase();
    QSqlDatabase::removeDatabase(g_mainterfaceConnectDatabaseName_1);//断开与数据库的连接

    //关闭数据库
    QSqlDatabase db2 = QSqlDatabase::database(g_mainterfaceConnectDatabaseName_2);
    db2.close();
    db2 = QSqlDatabase();
    QSqlDatabase::removeDatabase(g_mainterfaceConnectDatabaseName_2);//断开与数据库的连接

    delete ui;
}
//主界面风格
void MainInterface::initializeMainInterfaceSetStyleSheet()
{
    //背景动图
    QMovie *movie = new QMovie(":/Image/background.gif");
    ui->equipmentManageBackgroundLabel->setMovie(movie);
    movie->start();

    QPixmap icoPix;

    //equipmentManageBackgroundTitleLabel
    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->equipmentManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManageBackgroundTitleLabel->setScaledContents(true);
    ui->equipmentManageBackgroundTitleLabel->setPixmap(icoPix);

    icoPix.load(":/Image/examine.png");
    icoPix.scaled(ui->examineLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineLabel->setScaledContents(true);
    ui->examineLabel->setPixmap(icoPix);

    icoPix.load(":/Image/route.png");
    icoPix.scaled(ui->routeLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeLabel->setScaledContents(true);
    ui->routeLabel->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomework.png");
    icoPix.scaled(ui->tampingHomeworkLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkLabel->setScaledContents(true);
    ui->tampingHomeworkLabel->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomework.png");
    icoPix.scaled(ui->tampingHomeworkLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkLabel->setScaledContents(true);
    ui->tampingHomeworkLabel->setPixmap(icoPix);

    icoPix.load(":/Image/training.png");
    icoPix.scaled(ui->examineTrainingLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineTrainingLabel->setScaledContents(true);
    ui->examineTrainingLabel->setPixmap(icoPix);

    icoPix.load(":/Image/exam.png");
    icoPix.scaled(ui->examineExamLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamLabel->setScaledContents(true);
    ui->examineExamLabel->setPixmap(icoPix);

    icoPix.load(":/Image/training.png");
    icoPix.scaled(ui->routeTrainingLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeTrainingLabel->setScaledContents(true);
    ui->routeTrainingLabel->setPixmap(icoPix);

    icoPix.load(":/Image/exam.png");
    icoPix.scaled(ui->routeExamLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamLabel->setScaledContents(true);
    ui->routeExamLabel->setPixmap(icoPix);

    icoPix.load(":/Image/training.png");
    icoPix.scaled(ui->tampingHomeworkTrainingLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkTrainingLabel->setScaledContents(true);
    ui->tampingHomeworkTrainingLabel->setPixmap(icoPix);

    icoPix.load(":/Image/exam.png");
    icoPix.scaled(ui->tampingHomeworkExamLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamLabel->setScaledContents(true);
    ui->tampingHomeworkExamLabel->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentStatusBackground.png");
    icoPix.scaled(ui->equipmentStatusBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentStatusBackgroundLabel->setScaledContents(true);
    ui->equipmentStatusBackgroundLabel->setPixmap(icoPix);

    icoPix.load(":/Image/examineEquipmentOffline.png");
    icoPix.scaled(ui->examineEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineEquipmentStatusLabel->setScaledContents(true);
    ui->examineEquipmentStatusLabel->setPixmap(icoPix);


    icoPix.load(":/Image/routeEquipmentOffline.png");
    icoPix.scaled(ui->routeEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeEquipmentStatusLabel->setScaledContents(true);
    ui->routeEquipmentStatusLabel->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkEquipmentOffline.png");
    icoPix.scaled(ui->tampingHomeworkEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkEquipmentStatusLabel->setScaledContents(true);
    ui->tampingHomeworkEquipmentStatusLabel->setPixmap(icoPix);

    icoPix.load(":/Image/lowerComputerEquipmentOffline.png");
    icoPix.scaled(ui->lowerComputerEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->lowerComputerEquipmentStatusLabel->setScaledContents(true);
    ui->lowerComputerEquipmentStatusLabel->setPixmap(icoPix);


    icoPix.load(":/Image/examineExamManagePage.png");
    icoPix.scaled(ui->examineExamManagePageLabel_0->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManagePageLabel_0->setScaledContents(true);
    ui->examineExamManagePageLabel_0->setPixmap(icoPix);

    icoPix.load(":/Image/routeExamManagePage.png");
    icoPix.scaled(ui->routeExamManagePageLabel_0->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManagePageLabel_0->setScaledContents(true);
    ui->routeExamManagePageLabel_0->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkExamManagePage.png");
    icoPix.scaled(ui->tampingHomeworkExamManagePageLabel_0->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamManagePageLabel_0->setScaledContents(true);
    ui->tampingHomeworkExamManagePageLabel_0->setPixmap(icoPix);

    //结束环车检车提示显示
    icoPix.load(":/Image/endEquipmentActivity.png");
    icoPix.scaled(ui->endExamineEquipmentLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->endExamineEquipmentLabel->setScaledContents(true);
    ui->endExamineEquipmentLabel->setPixmap(icoPix);
    ui->endExamineEquipmentLabel->hide();

    icoPix.scaled(ui->endRouteEquipmentLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->endRouteEquipmentLabel->setScaledContents(true);
    ui->endRouteEquipmentLabel->setPixmap(icoPix);
    ui->endRouteEquipmentLabel->hide();

    icoPix.scaled(ui->endTampingHomeworkEquipmentLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->endTampingHomeworkEquipmentLabel->setScaledContents(true);
    ui->endTampingHomeworkEquipmentLabel->setPixmap(icoPix);
    ui->endTampingHomeworkEquipmentLabel->hide();


}
//运行前检查界面风格
void MainInterface::initializeExamineExamManagePageSetStyleSheet()
{
    QPixmap icoPix;

    icoPix.load(":/Image/routeExamManagePage.png");
    icoPix.scaled(ui->routeExamManagePageLabel_1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManagePageLabel_1->setScaledContents(true);
    ui->routeExamManagePageLabel_1->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkExamManagePage.png");
    icoPix.scaled(ui->tampingHomeworkExamManagePageLabel_1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamManagePageLabel_1->setScaledContents(true);
    ui->tampingHomeworkExamManagePageLabel_1->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentManagePage.png");
    icoPix.scaled(ui->equipmentManagePageLabel_1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManagePageLabel_1->setScaledContents(true);
    ui->equipmentManagePageLabel_1->setPixmap(icoPix);

    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->examineExamManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManageBackgroundTitleLabel->setScaledContents(true);
    ui->examineExamManageBackgroundTitleLabel->setPixmap(icoPix);

    icoPix.load(":/Image/background.png");
    icoPix.scaled(ui->examineExamManageBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManageBackgroundLabel->setScaledContents(true);
    ui->examineExamManageBackgroundLabel->setPixmap(icoPix);


}
//线路驾驶界面风格
void MainInterface::initializeRouteExamManagePageSetStyleSheet()
{
    QPixmap icoPix;

    icoPix.load(":/Image/examineExamManagePage.png");
    icoPix.scaled(ui->examineExamManagePageLabel_2->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManagePageLabel_2->setScaledContents(true);
    ui->examineExamManagePageLabel_2->setPixmap(icoPix);

    icoPix.load(":/Image/tampingHomeworkExamManagePage.png");
    icoPix.scaled(ui->tampingHomeworkExamManagePageLabel_2->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomeworkExamManagePageLabel_2->setScaledContents(true);
    ui->tampingHomeworkExamManagePageLabel_2->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentManagePage.png");
    icoPix.scaled(ui->equipmentManagePageLabel_2->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManagePageLabel_2->setScaledContents(true);
    ui->equipmentManagePageLabel_2->setPixmap(icoPix);


    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->routeExamManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManageBackgroundTitleLabel->setScaledContents(true);
    ui->routeExamManageBackgroundTitleLabel->setPixmap(icoPix);

    icoPix.load(":/Image/background.png");
    icoPix.scaled(ui->routeExamManageBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManageBackgroundLabel->setScaledContents(true);
    ui->routeExamManageBackgroundLabel->setPixmap(icoPix);
}
//捣鼓作业界面风格
void MainInterface::initializeTampingHomeworkExamManagePageSetStyleSheet()
{
    QPixmap icoPix;

    //equipmentManageBackgroundTitleLabel
    icoPix.load(":/Image/examineExamManagePage.png");
    icoPix.scaled(ui->examineExamManagePageLabel_3->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->examineExamManagePageLabel_3->setScaledContents(true);
    ui->examineExamManagePageLabel_3->setPixmap(icoPix);

    icoPix.load(":/Image/routeExamManagePage.png");
    icoPix.scaled(ui->routeExamManagePageLabel_3->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->routeExamManagePageLabel_3->setScaledContents(true);
    ui->routeExamManagePageLabel_3->setPixmap(icoPix);

    icoPix.load(":/Image/equipmentManagePage.png");
    icoPix.scaled(ui->equipmentManagePageLabel_3->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->equipmentManagePageLabel_3->setScaledContents(true);
    ui->equipmentManagePageLabel_3->setPixmap(icoPix);

    icoPix.load(":/Image/background.png");
    icoPix.scaled(ui->tampingHomworkExamManageBackgroundLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomworkExamManageBackgroundLabel->setScaledContents(true);
    ui->tampingHomworkExamManageBackgroundLabel->setPixmap(icoPix);

    icoPix.load(":/Image/backupgroundTitle.png");
    icoPix.scaled(ui->tampingHomworkExamManageBackgroundTitleLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->tampingHomworkExamManageBackgroundTitleLabel->setScaledContents(true);
    ui->tampingHomworkExamManageBackgroundTitleLabel->setPixmap(icoPix);

}
//运行前检查界面的功能
void MainInterface::initializeExamineExamManagePageFunction()
{
    // //发送
    // connect(ui->pushButton, &QPushButton::clicked, this, [&](){
    //     m_server->writeData(ui->lineEdit->text());
    // });

    // //全部发送
    // connect(ui->pushButton_2, &QPushButton::clicked, this, [&](){
    //     bool ok = true;
    //     QString str = ui->lineEdit_2->text();
    //     int num = str.toInt(&ok, 10);

    //     m_server->writeData(clientConnectedList[num].first, clientConnectedList[num].second, ui->lineEdit->text());
    // });

    //显示鼠标显示tableView上的文字信息
    //开启界面鼠标捕获功能
    ui->examTableView_1->viewport()->setMouseTracking(true);
    connect(ui->examTableView_1, &QTableView::entered,
            this, [](const QModelIndex &index)
            {
                if(index.isValid() == false) return;
                else{
                    // qDebug()<<"index.data().toString():"<<index.data().toString();
                    QToolTip::showText(QCursor::pos(), index.data().toString());
                }
            }
            );

    //1 数据模型
    m_examineExamTableDataModel = new QStandardItemModel(this);
    //2 选择模型
    m_examineExamSelectionModel = new QItemSelectionModel(m_examineExamTableDataModel);
    //3 设置模型
    ui->examTableView_1->setModel(m_examineExamTableDataModel);
    ui->examTableView_1->setSelectionModel(m_examineExamSelectionModel);

    //选择行为
    ui->examTableView_1->setSelectionBehavior (QAbstractItemView::SelectRows);
    //ui->recordsTableView->setSelectionMode ( QAbstractItemView::SingleSelection);
    ui->examTableView_1->setAlternatingRowColors(true);

    //隐藏左边的列名
    ui->examTableView_1->verticalHeader()->hide();

    //根据内容自适应宽度
    ui->examTableView_1->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    //ui->examTableView_1->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->examTableView_1->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

    //设置最大和最小列宽
    ui->examTableView_1->horizontalHeader()->setMinimumSectionSize(104);
    ui->examTableView_1->horizontalHeader()->setMaximumSectionSize(800);

    ui->examTableView_1->setStyleSheet("QTableView{background-color: rgb(64, 143, 212);color:black;}");//rgba(64, 143, 212, 30%);

    //不可编辑列
    ui->examTableView_1->setItemDelegateForColumn(0, &p0_m_readOnlyDelegate);
    ui->examTableView_1->setItemDelegateForColumn(1, &p0_m_readOnlyDelegate);
    ui->examTableView_1->setItemDelegateForColumn(2, &p0_m_readOnlyDelegate);
    ui->examTableView_1->setItemDelegateForColumn(3, &p0_m_readOnlyDelegate);
   // ui->examTableView_1->setItemDelegateForColumn(4, &p0_m_readOnlyDelegate);//执行结果
    ui->examTableView_1->setItemDelegateForColumn(5, &p0_m_readOnlyDelegate);
    //ui->examTableView_1->setItemDelegateForColumn(6, &p0_m_readOnlyDelegate);
    //ui->examTableView_1->setItemDelegateForColumn(7, &p0_m_readOnlyDelegate);


    ui->examTableView_1->hide();

    //恢复可编辑
    // int cols = p0_m_tableDataModel->columnCount();
    // QAbstractItemDelegate* defaultdelegate = ui->recordsTableView->itemDelegateForColumn(0);
    // for(int loop = 1; loop < cols ;loop ++)
    // {
    //     QAbstractItemDelegate* nowdelegate = ui->recordsTableView->itemDelegateForColumn(loop);
    //     ReadOnlyDelegate * showdelegate = static_cast<ReadOnlyDelegate *>(nowdelegate);
    //     if(showdelegate)            //表示当前的代理是自定义的代理
    //     {
    //         ui->recordsTableView->setItemDelegateForColumn(loop, defaultdelegate);
    //     }
    // }


    //阻塞信号
    ui->examTableView_1->itemDelegate()->blockSignals(true);

    ui->examineExamGradeSubmitPushButton->hide();

    //   showPartExamTable(ExamType::ExamineExamOne);
    // showAllExamTable(ExamType::ExamineExamOne);

    //提交考试成绩按钮
    connect(ui->examineExamGradeSubmitPushButton, &QPushButton::clicked,
            this, [&](){
                //把主观评分写入到数据库
                QSqlQuery query(QSqlDatabase::database(g_mainterfaceConnectDatabaseName_2));
                QString sql = QString("UPDATE %1 SET step_result = ? WHERE id = ?").arg(g_examineExamTableName);
                QVariantList idList;
                QVariantList stepResultList;
                for(int row = 0;row < m_examineExamTableDataModel->rowCount();row++){

                    idList.append(m_examineExamTableDataModel->data(m_examineExamTableDataModel->index(row, 0)));
                    stepResultList.append(static_cast<QComboBox *>(ui->examTableView_1->indexWidget(m_examineExamTableDataModel->index(row, 4)))->currentText());
                   // stepResultList.append(m_examineExamTableDataModel->data(m_examineExamTableDataModel->index(row, 5)));
                }
                query.prepare(sql);
                query.addBindValue( stepResultList);
                query.addBindValue(idList);
                if(query.execBatch()){

                    if(isActiveEndingExamineEquipmentExam == true){//主动结束考试（设备管理端）
                        qDebug()<<"主动结束考试";
                        QHash<QString, QList<int>> faultType;
                        emit m_server->sendUserLogInformation(ClientHashEnum::ExamineExamUnityEquipment, ExamType::ExitType, 0, "", faultType);
                        ui->examineExamGradeSubmitPushButton->hide();
                        m_waitProcessBar->startTimer();
                    }else{//被动结束考试（unity端）
                        qDebug()<<"被动结束考试";
                        qDebug()<<"m_server->calculateExamSituation(ExamType::ExamineExam)：计算考试情况";
                        emit m_server->calculateExamSituation(ExamType::ExamineExam);
                    }
                }else{
                    qDebug()<<query.lastError().databaseText();
                }

            });


    //隐藏成绩提交按钮
    ui->examineExamGradeSubmitPushButton->hide();

}

//事件过滤器
bool MainInterface::eventFilter(QObject *obj, QEvent *event)
{
    //切换到设备管理界面
    if(obj == ui->equipmentManagePageLabel_1){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(0);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->equipmentManagePageLabel_2){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(0);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->equipmentManagePageLabel_3){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(0);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->examineExamManagePageLabel_0){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(1);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->examineExamManagePageLabel_2){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(1);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->examineExamManagePageLabel_3){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(1);
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->routeExamManagePageLabel_0){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(2);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->routeExamManagePageLabel_1){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(2);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->routeExamManagePageLabel_3){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(2);
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->tampingHomeworkExamManagePageLabel_0){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(3);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->tampingHomeworkExamManagePageLabel_1){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(3);
                return true;
            }else return false;
        }else return false;
    }
    else if(obj == ui->tampingHomeworkExamManagePageLabel_2){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                ui->stackedWidget->setCurrentIndex(3);
                return true;
            }else return false;
        }else return false;
    }

    ////功能按钮

    //训练模式
    else if(obj == ui->tampingHomeworkTrainingLabel){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                if(m_tampingHomeworkEquipmentStatus == false){
                    auto button = QMessageBox::information(this,  tr("信息提示"),
                                                           QString("请等待捣固端上线后，再操作，谢谢。"),  QString("确定"),  0);
                    if (button == 0) {//修改记录信息

                    }
                }
                else{
                    if(m_tampingHomeworkEquipmentLoginStatus == false){
                        emit show2LoginDialog(ClientHashEnum::TampingHomeworkEquipment, ExamType::TampingHomeworkExam, ExamPatternType::TrainingType);
                    }
                }
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->examineTrainingLabel){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                if(m_examineExamEquipmentStatus == false){
                    auto button = QMessageBox::information(this,  tr("信息提示"),
                                                           QString("请等待运行前检查端上线后，再操作，谢谢。"),  QString("确定"),  0);
                    if (button == 0) {//修改记录信息

                    }
                }
                else{
                    if(m_examineExamEquipmentLoginStatus == false){
                        emit show2LoginDialog(ClientHashEnum::ExamineExamUnityEquipment, ExamType::ExamineExam, ExamPatternType::TrainingType);
                    }
                }
                return true;
            }else return false;
        }else return false;
    }

    else if(obj == ui->routeTrainingLabel){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                if(m_routeExamEquipmentStatus == false){
                    auto button = QMessageBox::information(this,  tr("信息提示"),
                                                           QString("请等待线路驾驶端上线后，再操作，谢谢。"),  QString("确定"),  0);
                    if (button == 0) {//修改记录信息

                    }
                }
                else{
                    if(m_routeExamEquipmentLoginStatus == false){
                        emit show2LoginDialog(ClientHashEnum::TampingHomeworkEquipment, ExamType::TampingHomeworkExam, ExamPatternType::TrainingType);
                    }
                }
                return true;
            }else return false;
        }else return false;
    }

    //考试模式
    else if(obj == ui->examineExamLabel){//检查与实验考试模式
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){

                if(m_examineExamEquipmentStatus == false){
                    auto button = QMessageBox::information(this,  tr("信息提示"),
                                                           QString("请等待运行前检查端上线后，再操作，谢谢。"),  QString("确定"),  0);
                    if (button == 0) {//修改记录信息

                    }
                }else{
                    if(m_routeExamEquipmentLoginStatus == false){
                        emit show2LoginDialog(ClientHashEnum::ExamineExamUnityEquipment, ExamType::ExamineExam, ExamPatternType::ExamType);
                    }else{

                    }
                }
                return true;
            }else return false;
        }else return false;
    }

    //结束练习模式
    else if(obj == ui->endExamineEquipmentLabel){
        if(event->type() == QEvent::MouseButtonPress){
            QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
            if(mouseEvent->button() == Qt::LeftButton){
                if(m_examineExamEquipmentStatus == true){
                    auto button = QMessageBox::question(this,  tr("信息提示"),
                                                        QString("是否使%1退出环车检查端登录？").arg(g_examineEquipmentUsername),  QString("确定"), QString("取消"), 0);

                    if (button == 0) {
                        if(g_isExecuteEquipmentExam){//考试模式
                            auto button2 = QMessageBox::question(this,  tr("信息提示"),
                                                                 QString("是否进行%1的环车检查考试的主观评分？").arg(g_examineEquipmentUsername),  QString("是"), QString("否"), 0);

                            if(g_isExecuteEquipmentExamTimeout){
                                insertExamTableTimeoutResult(g_examineExamTableName);

                                g_insertExecuteEquipmentExamTimeoutRecord = true;
                            }

                            if(button2 == 0){//主观评分：跳转到评分页面
                                isActiveEndingExamineEquipmentExam = true;

                                ui->examineExamGradeSubmitPushButton->show();

                                showAllExamTable(ExamType::ExamineExam);

                                ui->stackedWidget->setCurrentIndex(1);
                            }else{
                                QHash<QString, QList<int>> faultType;

                                emit m_server->sendUserLogInformation(ClientHashEnum::ExamineExamUnityEquipment, ExamType::ExitType, 0, "", faultType);

                                m_waitProcessBar->startTimer();
                            }
                        }else{//练习模式
                            auto button2 = QMessageBox::question(this,  tr("信息提示"),
                                                                 QString("是否结束%1的环车检查练习模式？").arg(g_examineEquipmentUsername),  QString("是"), QString("否"), 0);

                            if(button2 == 0){
                                QHash<QString, QList<int>> faultType;

                                emit m_server->sendUserLogInformation(ClientHashEnum::ExamineExamUnityEquipment, ExamType::ExitType, 0, "", faultType);

                                m_waitProcessBar->startTimer();
                            }else{

                            }
                        }

                    }
                }else{
                    auto button = QMessageBox::information(this,  tr("信息提示"),
                                                           QString("环车检查端已断开连接，请等待环车检查端重新连接。"),  QString("确定"),  0);
                    if(button == 0){

                    }
                }

                return true;
            }else return false;
        }else return false;
    }

    else return MainInterface::eventFilter(obj, event);
}

void MainInterface::sendLoginInformation(QString username, int equipmentType, int examType, int examPatternType, QHash<QString, QList<int> > faultType)
{
    //临时存储设备登录信息
    m_saveUsername = username;
    m_saveEquipmentType = equipmentType;
    m_saveExamType = examType;
    m_saveExamPatternType = examPatternType;
    m_saveFaultType = faultType;

    emit m_server->sendUserLogInformation(equipmentType, examType, examPatternType, username, faultType);

    m_waitProcessBar->startTimer();
}
//获得本机ip，建立服务器连接
void MainInterface::startTcpServer()
{
    m_listenIp = getLocalIP();
    qDebug()<<"目前获得的ip:"<<m_listenIp;
    if(m_listenIp == "127.0.0.1" ){//如果是本地ip，则一直重复要求联网
        while(true){
            if(m_serverStatus == true){
                break;
            }
            auto button = QMessageBox::question(this,  tr("信息提示"),
                                                QString("是否已连接局域网络？"),  QString("确定"),  0);
            if (button == 0) {
                startTcpServer();
            }
        }
    }else{
        while(m_listenPort < 20000){//遍历寻找可以监听的端口
            if(m_server->start(m_listenIp, m_listenPort)){
                qDebug()<<QString("开始监听%1 : %2").arg(m_listenIp).arg(m_listenPort);
                m_serverStatus = true;

                QSqlQuery query(QSqlDatabase::database(g_mainterfaceConnectDatabaseName_1));
                //REPLACE INTO users (id,name,age) VALUES(123, '贾斯丁比伯', 22);
                QString sql = QString("REPLACE INTO equipment_server_information (serial_number, ip, port, online, train_model) "
                                      "VALUES(\'%1\', \'%2\', %3, %4, \'%5\')")
                                  .arg(QString("00000002"))
                                  .arg(m_listenIp)
                                  .arg(m_listenPort)
                                  .arg(1)
                                  .arg("DCL-32k");

                if(!query.exec(sql)){
                    qDebug()<<query.lastError().databaseText();
                }

                break;
            }else{
                m_listenPort++;
            }
        }
    }
}

//初始化服务器套接字
void MainInterface::initializeTcpServer()
{
    //m_server = new TcpServer(this);
    m_server = new TcpServer();


    ///---->客户端套接字

    //关闭套接字
    connect(this, &MainInterface::closeServer,
            m_server, &TcpServer::closeServer);

    connect(this, &MainInterface::closeOneSocket,
            m_server, &TcpServer::closeOneSocket);

    connect(this, &MainInterface::closeAllSocket,
            m_server, &TcpServer::closeAllSocket);



    ///--->主界面
    connect(m_server, &TcpServer::acceptError,
            this, [&](QAbstractSocket::SocketError socketError){
                //qDebug()<<m_server->errorString();
                qDebug()<<"socketError:"<<socketError;
            });

    //客户端连接
    connect(m_server, &TcpServer::clientConnected,
            this, &MainInterface::clientConnected);

    //客户端断开连接
    connect(m_server, &TcpServer::clientDisconnected,
            this, &MainInterface::clientDisconnected);

    //发送的数据
    connect(m_server, &TcpServer::sendSocketData,
            this, [](const QString &ip, int port, const QString &data){
                qDebug()<<QString("发送客户端 %1 : %2 ：%3").arg(ip).arg(port).arg(data);
            });

    //接收到的数据
    connect(m_server,  &TcpServer::receiveData,
            this, [](const QString &ip, int port, const QString &data){
                qDebug()<<QString("收到客户端 %1 : %2 ：%3").arg(ip).arg(port).arg(data);
            });



    //传递unity客户端的状态(在线、离线、已登录、未登录);株所设备的状态
    connect(m_server, &TcpServer::conveyEquipmentStatusType,
            this, &MainInterface::dealConveyEquipmentStatusType);

    //显示考试情况
    connect(m_server, &TcpServer::sendExamSituation,
            this, &MainInterface::dealExamSituation);

    //得到主观成绩
    connect(m_server, &TcpServer::getExamStepSubjectivePoint,
            this, [&](int examType){
                qDebug()<<"得到主观成绩";


                if(examType == ExamType::ExamineExam){
                    if(g_isExecuteEquipmentExam){
                        auto button2 = QMessageBox::question(this,  tr("信息提示"),
                                                             QString("是否进行%1的环车检查考试的主观评分？").arg(g_examineEquipmentUsername),  QString("是"), QString("否"), 0);

                        if(g_isExecuteEquipmentExamTimeout){
                            insertExamTableTimeoutResult(g_examineExamTableName);

                            g_insertExecuteEquipmentExamTimeoutRecord = true;
                        }

                        if(button2 == 0){//进行主观评分
                            isActiveEndingExamineEquipmentExam = false;

                            showAllExamTable(ExamType::ExamineExam);

                            ui->examineExamGradeSubmitPushButton->show();

                            ui->stackedWidget->setCurrentIndex(1);
                        }else{//不进行主观评分
                            // qDebug()<<"不进行主观评分: emit m_server->sendExamineOneExamFinalGrade()1";
                            emit m_server->calculateExamSituation(ExamType::ExamineExam);
                        }
                    }
                }

            });

    //显示部分表格
    connect(m_server, &TcpServer::showPartExamTable,
            this, &MainInterface::showPartExamTable);
}

//处理设备登录状态
void MainInterface::dealConveyEquipmentStatusType(int status)
{
    qDebug()<<"&TcpServer::conveyEquipmentStatusType"<<QThread::currentThreadId() << QThread::currentThread();
    qDebug()<<"status:"<<status<<" ;"<<EquipmentStatusType::ExamineExamUnityEquipmentLogOut;

    QPixmap icoPix;

    if(status == EquipmentStatusType::ExamineExamUnityEquipmentOnline){
        m_examineExamEquipmentStatus = true;

        icoPix.load(":/Image/examineEquipmentOnline.png");
        icoPix.scaled(ui->examineEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->examineEquipmentStatusLabel->setScaledContents(true);
        ui->examineEquipmentStatusLabel->setPixmap(icoPix);
    }else if(status == EquipmentStatusType::ExamineExamUnityEquipmentOffline){
        icoPix.load(":/Image/examineEquipmentOffline.png");
        icoPix.scaled(ui->examineEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->examineEquipmentStatusLabel->setScaledContents(true);
        ui->examineEquipmentStatusLabel->setPixmap(icoPix);
    }else if(status == EquipmentStatusType::ExamineExamUnityEquipmentLogIn){
        loginStatusSuccess();
    }else if(status == EquipmentStatusType::ExamineExamUnityEquipmentLogOut){
        m_examineExamEquipmentLoginStatus = false;

        ui->endExamineEquipmentLabel->hide();
        ui->examineEquipmentInformationLabel->hide();

        m_waitProcessBar->stopTimer();
    }

    else if(status == EquipmentStatusType::RouteExamUnityEquipmentOnline){
        m_routeExamEquipmentStatus = true;

        icoPix.load(":/Image/routeEquipmentOnline.png");
        icoPix.scaled(ui->routeEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->routeEquipmentStatusLabel->setScaledContents(true);
        ui->routeEquipmentStatusLabel->setPixmap(icoPix);
    }else if(status == EquipmentStatusType::RouteExamUnityEquipmentOffline){
        icoPix.load(":/Image/routeEquipmentOffline.png");
        icoPix.scaled(ui->routeEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->routeEquipmentStatusLabel->setScaledContents(true);
        ui->routeEquipmentStatusLabel->setPixmap(icoPix);
    }else if(status == EquipmentStatusType::RouteExamUnityEquipmentLogIn){
        loginStatusSuccess();
    }else if(status == EquipmentStatusType::RouteExamUnityEquipmentLogOut){
        m_routeExamEquipmentLoginStatus = false;

        ui->endRouteEquipmentLabel->hide();
        ui->routeEquipmentInformationLabel->hide();

        m_waitProcessBar->stopTimer();
    }

    else if(status == EquipmentStatusType::TampingHomeworkEquipmentOnline){
        m_tampingHomeworkEquipmentStatus = true;

        icoPix.load(":/Image/tampingHomeworkEquipmentOnline.png");
        icoPix.scaled(ui->tampingHomeworkEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->tampingHomeworkEquipmentStatusLabel->setScaledContents(true);
        ui->tampingHomeworkEquipmentStatusLabel->setPixmap(icoPix);
    }else if(status == EquipmentStatusType::TampingHomeworkEquipmentOffline){
        icoPix.load(":/Image/tampingHomeworkEquipmentOffline.png");
        icoPix.scaled(ui->tampingHomeworkEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->tampingHomeworkEquipmentStatusLabel->setScaledContents(true);
        ui->tampingHomeworkEquipmentStatusLabel->setPixmap(icoPix);
    }else if(status == EquipmentStatusType::TampingHomeworkEquipmentLogIn){
        loginStatusSuccess();

    }else if(status == EquipmentStatusType::TampingHomeworkEquipmentLogOut){
        m_tampingHomeworkEquipmentLoginStatus = false;

        ui->endTampingHomeworkEquipmentLabel->hide();
        ui->tampingHomeworkEquipmentInformationLabel->hide();

        m_waitProcessBar->stopTimer();
    }

    else if(status == EquipmentStatusType::LowerComputerEquipmentOnline){

        icoPix.load(":/Image/lowerComputerEquipmentOnline.png");
        icoPix.scaled(ui->lowerComputerEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->lowerComputerEquipmentStatusLabel->setScaledContents(true);
        ui->lowerComputerEquipmentStatusLabel->setPixmap(icoPix);

    }else if(status == EquipmentStatusType::LowerComputerEquipmentOffline){
        icoPix.load(":/Image/lowerComputerEquipmentOffline.png");
        icoPix.scaled(ui->lowerComputerEquipmentStatusLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->lowerComputerEquipmentStatusLabel->setScaledContents(true);
        ui->lowerComputerEquipmentStatusLabel->setPixmap(icoPix);

    }

}
//显示考试情况的弹窗
void MainInterface::dealExamSituation(int examtype, QHash<QString, int> examSubstepNumberRecord)
{
    ////二次调用
    qDebug()<<"显示最终的考试成绩【二次调用】:";
    qDebug()<<"g_isShowRouteEquipmentExamGrade:";

    QString tipText  = QString("学员");
    if(examtype == ExamType::ExamineExam){
        tipText += g_examineEquipmentUsername;
        tipText += QString("的运行前检查的考试情况为：\n 正确: %1; \n 错误: %2; \n 未做: %3;")
                       .arg(examSubstepNumberRecord["rightStep"])
                        .arg(examSubstepNumberRecord["wrongStep"])
                        .arg(examSubstepNumberRecord["unDoneStep"]);

        ui->examineExamGradeSubmitPushButton->hide();
        ui->stackedWidget->setCurrentIndex(0);
        ui->examTableView_1->hide();

    }else if(examtype == ExamType::RouteExam){
        tipText += g_routeEquipmentUsername;
        tipText += QString("的线路驾驶的考试情况为：\n 正确: %1; \n 错误: %2; \n 未做: %3;")
                       .arg(examSubstepNumberRecord["rightStep"])
                       .arg(examSubstepNumberRecord["wrongStep"])
                       .arg(examSubstepNumberRecord["unDoneStep"]);

        ui->routeEquipmentExamGradeSubmitPushButton->hide();
        ui->stackedWidget->setCurrentIndex(0);
        ui->examTableView_2->hide();

    }else if(examtype == ExamType::TampingHomeworkExam){
        tipText += g_routeEquipmentUsername;
        tipText += QString("的捣固作业的考试情况为：\n 正确: %1; \n 错误: %2; \n 未做: %3;")
                       .arg(examSubstepNumberRecord["rightStep"])
                       .arg(examSubstepNumberRecord["wrongStep"])
                       .arg(examSubstepNumberRecord["unDoneStep"]);

        ui->routeEquipmentExamGradeSubmitPushButton->hide();
        ui->stackedWidget->setCurrentIndex(0);
        ui->examTableView_2->hide();
    }

    auto button = QMessageBox::information(this,  tr("信息提示"),
                                           tipText,  QString("确定"), 0);
    if (button == 0){

    }

}

void MainInterface::mainInterfaceFunction()
{

}

//成功登录
void MainInterface::loginStatusSuccess()
{
    m_waitProcessBar->stopTimer();

    QPixmap icoPix;
    QString tipText;

    if(m_saveEquipmentType == ClientHashEnum::ExamineExamUnityEquipment){

        if(m_saveExamPatternType == ExamPatternType::TrainingType){
            tipText = QString("学员%1正在环车检查端练习").arg(g_examineEquipmentUsername);
        }else if(m_saveExamPatternType == ExamPatternType::ExamType){
            tipText = QString("学员%1正在环车检查端考试").arg(g_examineEquipmentUsername);
        }

        //在提示图上绘制文字
        icoPix.load(":/Image/informationBackground.png");
        QPainter painter(&icoPix);
        painter.begin(&icoPix);
        painter.setPen(Qt::white);
        //设置字体大小.另可以根据画笔改变颜色等属性
        QFont font = painter.font();
        font.setPixelSize(40);//改变字体大小
        // font.setFamily("Microsoft YaHei");
        painter.setFont(font);
        //将文字写在图片上，例如是int型的数字123，居中
        painter.drawText(icoPix.rect(), Qt::AlignCenter, tipText.toStdString().c_str());
        painter.end();

        icoPix.scaled(ui->examineEquipmentInformationLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->examineEquipmentInformationLabel->setScaledContents(true);
        ui->examineEquipmentInformationLabel->setPixmap(icoPix);

        //显示环车检车设备提示信息
        ui->endExamineEquipmentLabel->show();
        ui->examineEquipmentInformationLabel->show();

        m_examineExamEquipmentLoginStatus = true;

        // emit m_server->sendUserLogInformation(ClientHashEnum::ExamineExamUnityEquipment, m_saveExamType, m_saveExamPatternType, m_saveUsername, m_saveFaultType);

    }else if(m_saveEquipmentType == ClientHashEnum::RouteExamUnityEquipment){

        tipText = QString("学员%1正在驾驶端进行线路驾驶").arg(g_routeEquipmentUsername);

        if(m_saveExamPatternType == ExamPatternType::TrainingType){
            tipText += "的练习";
        }else if(m_saveExamPatternType == ExamPatternType::ExamType){
            tipText += "的考试";
        }

        icoPix.load(":/Image/informationBackground.png");

        QPainter painter;
        painter.begin(&icoPix);
        painter.setPen(Qt::white);
        //设置字体大小.另可以根据画笔改变颜色等属性
        QFont font = painter.font();
        // font.setFamily("Microsoft YaHei");
        font.setPixelSize(40);//改变字体大小
        painter.setFont(font);
        //将文字写在图片上，例如是int型的数字123，居中
        painter.drawText(icoPix.rect(), Qt::AlignCenter,tipText.toStdString().c_str());
        painter.end();
        icoPix.scaled(ui->routeEquipmentInformationLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->routeEquipmentInformationLabel->setScaledContents(true);
        ui->routeEquipmentInformationLabel->setPixmap(icoPix);

        //提示信息显示
        ui->endRouteEquipmentLabel->show();
        ui->routeEquipmentInformationLabel->show();

        m_routeExamEquipmentLoginStatus = true;

        // emit m_server->sendUserLogInformation(ClientHashEnum::RouteExamUnityEquipment, m_saveExamType, m_saveExamPatternType, m_saveUsername, m_saveFaultType);

    }else if(m_saveEquipmentType == ClientHashEnum::TampingHomeworkEquipment){

        tipText = QString("学员%1正在作业端进行捣固作业").arg(g_routeEquipmentUsername);

        if(m_saveExamPatternType == ExamPatternType::TrainingType){
            tipText += "的练习";
        }else if(m_saveExamPatternType == ExamPatternType::ExamType){
            tipText += "的考试";
        }

        icoPix.load(":/Image/informationBackground.png");

        QPainter painter;
        painter.begin(&icoPix);
        painter.setPen(Qt::white);
        //设置字体大小.另可以根据画笔改变颜色等属性
        QFont font = painter.font();
        // font.setFamily("Microsoft YaHei");
        font.setPixelSize(40);//改变字体大小
        painter.setFont(font);
        //将文字写在图片上，例如是int型的数字123，居中
        painter.drawText(icoPix.rect(), Qt::AlignCenter,tipText.toStdString().c_str());
        painter.end();
        icoPix.scaled(ui->routeEquipmentInformationLabel->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ui->routeEquipmentInformationLabel->setScaledContents(true);
        ui->routeEquipmentInformationLabel->setPixmap(icoPix);

        //提示信息显示
        ui->endRouteEquipmentLabel->show();
        ui->routeEquipmentInformationLabel->show();

        m_routeExamEquipmentLoginStatus = true;

        // emit m_server->sendUserLogInformation(ClientHashEnum::RouteExamUnityEquipment, m_saveExamType, m_saveExamPatternType, m_saveUsername, m_saveFaultType);

    }
}

void MainInterface::initializeTableFieldHash()
{
    // m_tableName2UseHash["route_exam"] = "线路考试成绩信息表";

    // QPair<QString, QString> pair;
    // m_tableFieldName2UseHash[QPair("route_exam", "id")] = "编号";
    // m_tableFieldName2UseHash[QPair("route_exam","execute_step_id")] = "步骤序号";
    // m_tableFieldName2UseHash[QPair("route_exam","exam_step_describe")] = "步骤描述";
    // m_tableFieldName2UseHash[QPair("route_exam","step_total_point")] = "步骤分值";
    // m_tableFieldName2UseHash[QPair("route_exam","step_object_point")] = "客观得分";
    // m_tableFieldName2UseHash[QPair("route_exam","step_subjective_point")] = "人工修正";
    // m_tableFieldName2UseHash[QPair("route_exam","step_final_point")] = "最终得分";
    // m_tableFieldName2UseHash[QPair("route_exam","error_reason")] = "错误原因";

    // m_use2TableNameHash["线路考试成绩信息表"] = "route_exam";

    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表", "编号")] = "id";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","步骤序号")] = "execute_step_id";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","步骤描述")] = "exam_step_describe";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","步骤分值")] = "step_total_point";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","客观得分")] = "step_object_point";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","人工修正")] = "step_subjective_point";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","最终得分")] = "step_final_point";
    // m_use2TableFieldNameHash[QPair("线路考试成绩信息表","错误原因")] = "error_reason";

    //
    QPair<QString, QString> pair;
    m_tableFieldName2UseHash[QPair("exam_template", "id")] = "编号";
    m_tableFieldName2UseHash[QPair("exam_template","execute_step_id")] = "步骤序号";
    m_tableFieldName2UseHash[QPair("exam_template","exam_step_describe")] = "步骤描述";
    m_tableFieldName2UseHash[QPair("exam_template","step_total_point")] = "步骤分值";
    m_tableFieldName2UseHash[QPair("exam_template","step_object_point")] = "客观得分";
    m_tableFieldName2UseHash[QPair("exam_template","step_subjective_point")] = "人工修正";
    m_tableFieldName2UseHash[QPair("exam_template","step_final_point")] = "最终得分";
    m_tableFieldName2UseHash[QPair("exam_template","error_reason")] = "错误原因";
    m_tableFieldName2UseHash[QPair("exam_template","step_result")] = "执行结果";
    m_tableFieldName2UseHash[QPair("exam_template","exam_step_total_describe")] = "部件方位";



}

//表格全部展示
void MainInterface::showAllExamTable(int examType)
{
    QString tableName;

    QString sql;

    if(examType == ExamType::ExamineExam){
        tableName = g_examineExamTableName;
        sql = QString("SELECT id, execute_step_id, exam_step_total_describe, exam_step_describe,"
                      //"step_total_point,step_object_point,step_subjective_point,step_final_point,"
                      "step_result, error_reason FROM %1 ORDER BY id ASC").arg(tableName);

        showExamineExamTableShowBySqlQuery(sql);
    }else if(examType == ExamType::RouteExam){
        tableName = g_routeExamTableName;
        sql = QString("SELECT id,execute_step_id,exam_step_describe,"
                      //"step_total_point,step_object_point,step_subjective_point,step_final_point,"
                      "step_result,error_reason FROM %1 ORDER BY id ASC").arg(tableName);

        qDebug()<<"sql:"<<sql;

        //showRouteExamTableShowBySqlQuery(sql);
    }else if(examType == ExamType::TampingHomeworkExam){
        tableName = g_tampingHomeworkTableName;
        sql = QString("SELECT id,execute_step_id,exam_step_describe,"
                      //"step_total_point,step_object_point,step_subjective_point,step_final_point,"
                      "step_result,error_reason FROM %1 ORDER BY id ASC").arg(tableName);

        //showRouteExamTableShowBySqlQuery(sql);
    }
}
//表格部分展示
void MainInterface::showPartExamTable(int examType)
{
    QString tableName;
    QString sql;

    if(examType == ExamType::ExamineExam){
        tableName = g_examineExamTableName;
        sql =   QString("SELECT id, execute_step_id, exam_step_total_describe, exam_step_describe,"
                     // "step_total_point,step_object_point,step_subjective_point,step_final_point,"
                      "step_result, error_reason FROM %1 "
                      "WHERE execute_step_id is not null "
                      "order by execute_step_id asc").arg(tableName);
        qDebug()<<sql;

        showExamineExamTableShowBySqlQuery(sql);
    }else if(examType == ExamType::RouteExam){
        tableName = g_routeExamTableName;
        sql =   QString("SELECT id,execute_step_id,exam_step_describe,"
                      "step_total_point,step_object_point,step_subjective_point,"
                      "step_final_point,error_reason FROM %1 "
                      "WHERE execute_step_id is not null "
                      "order by execute_step_id asc").arg(tableName);

        qDebug()<<"showPartExamTable(ExamType::RouteExam) sql:"<<sql;

        //showRouteExamTableShowBySqlQuery(sql);
    }else if(examType == ExamType::TampingHomeworkExam){
        tableName = g_tampingHomeworkTableName;
        sql =   QString("SELECT id,execute_step_id,exam_step_describe,"
                      "step_total_point,step_object_point,step_subjective_point,"
                      "step_final_point,error_reason FROM %1 "
                      "WHERE execute_step_id is not null "
                      "order by execute_step_id asc").arg(tableName);


       // showRouteExamTableShowBySqlQuery(sql);
    }

}

//运行前检查：根据sql语句
void MainInterface::showExamineExamTableShowBySqlQuery(QString sql)
{
    qDebug()<<"showExamineExamTableShowBySqlQuery：";
    m_examineExamTableDataModel->clear();
    //移除之前的数据
    m_examineExamTableDataModel->removeRows(0, m_examineExamTableDataModel->rowCount());
    //水平表头可见
    ui->examTableView_1->horizontalHeader()->setVisible(true);

    QSqlQuery query(QSqlDatabase::database(g_mainterfaceConnectDatabaseName_2));

    //设置表头
   // m_examineExamTableDataModel->setHorizontalHeaderItem(0, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "id")]));
   // m_examineExamTableDataModel->setHorizontalHeaderItem(1, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "execute_step_id")]));
    //m_examineExamTableDataModel->setHorizontalHeaderItem(2, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "exam_step_describe")]));
    // m_examineExamTableDataModel->setHorizontalHeaderItem(3, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "step_total_point")]));
    // m_examineExamTableDataModel->setHorizontalHeaderItem(4, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "step_object_point")]));
    // m_examineExamTableDataModel->setHorizontalHeaderItem(5, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "step_subjective_point")]));
    // m_examineExamTableDataModel->setHorizontalHeaderItem(6, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "step_final_point")]));
    //m_examineExamTableDataModel->setHorizontalHeaderItem(7, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "error_reason")]));
    ///
    m_examineExamTableDataModel->setHorizontalHeaderItem(0, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "id")]));
    m_examineExamTableDataModel->setHorizontalHeaderItem(1, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "execute_step_id")]));
    m_examineExamTableDataModel->setHorizontalHeaderItem(2, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "exam_step_total_describe")]));
    m_examineExamTableDataModel->setHorizontalHeaderItem(3, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "exam_step_describe")]));
    m_examineExamTableDataModel->setHorizontalHeaderItem(4, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "step_result")]));
    m_examineExamTableDataModel->setHorizontalHeaderItem(5, new QStandardItem(m_tableFieldName2UseHash[QPair(QString("exam_template"), "error_reason")]));



    if(query.exec(sql)){
        //设置行和列
        int row = 0;
        while(query.next()){
            row++;
        }
        query.seek(-1);

        m_examineExamTableDataModel->setRowCount(row);

        row = 0;
        //设置表中值
        while(query.next()){//ui->Page1_tableView->model()->headerData(i,Qt::Horizontal).toString();
            for(int colNum = 0;colNum < 6;colNum++){
                if(colNum == 4){
                    QComboBox *stepResultComboBox = new QComboBox(this);
                    stepResultComboBox->setStyleSheet("QComboBox{color:rgb(0, 0, 0);}");
                    QStringList itemList;
                    itemList <<"错误"<<"正确";
                    stepResultComboBox->addItems(itemList);
                    if(query.value(colNum).toString() == "正确"){
                        stepResultComboBox->setCurrentIndex(1);
                    }else{
                        stepResultComboBox->setCurrentIndex(0);
                    }


                    // connect(unitComboBox, &QComboBox::currentTextChanged,
                    //         this, [&](const QString &data){
                    //     QModelIndex curIndex =  m_routeExamSelectionModel->currentIndex();

                    //     int row = curIndex.row();
                    //     int col = curIndex.column();

                    // });

                     ui->examTableView_1->setIndexWidget(m_examineExamTableDataModel->index(row, colNum),  stepResultComboBox);

                }

                QModelIndex index =  m_examineExamTableDataModel->index(row, colNum);
                m_examineExamTableDataModel->setData(index, query.value(colNum), Qt::DisplayRole);
            }
            row++;
        }
    }else{
        qDebug()<<query.lastError().databaseText();
    }

    ui->examTableView_1->setModel(m_examineExamTableDataModel);
    ui->examTableView_1->show();

    ui->examTableView_1->itemDelegate()->blockSignals(false);
}

//插入超时记录
void MainInterface::insertExamTableTimeoutResult(QString tableName)
{
    qDebug()<<"插入线路考试超时内容";
    QString sql = QString("INSERT INTO %1 (id, execute_step_id, exam_step_number, exam_step_describe, "
                          "exam_substep_number ,step_total_point, step_deduct_point, step_object_point,"
                          " step_subjective_point, step_final_point, step_result, error_reason) VALUES ("
                          "\'0F0000\', NULL, \'0F00\', \'考试超过规定35min\',"
                          "\'none\', 0.0, 0.00, 0.00,"
                          "0.0, 0.00, \'错误\',\'考试超时\')").arg(tableName);

    QSqlQuery query(QSqlDatabase::database(g_mainterfaceConnectDatabaseName_2));

    if(!query.exec(sql)){
        qDebug()<<query.lastError().databaseText();
    }else{
        if(tableName == g_examineExamTableName){
            g_insertExecuteEquipmentExamTimeoutRecord = true;
        }else if(tableName == g_routeExamTableName){
            g_insertRouteEquipmentExamTimeoutRecord = true;
        }

    }
}

void MainInterface::clientConnected(const QString &ip, int port)
{
    qDebug()<<QString("客户端上线: %1 : %2").arg(ip).arg(QString::number(port));
    clientConnectedList.append(QPair(ip, port));

}

void MainInterface::clientDisconnected(const QString &ip, int port)
{
    qDebug()<<QString("客户端下线: %1 : %2").arg(ip).arg(QString::number(port));
    clientConnectedList.removeOne(QPair(ip, port));
}

//初始化网络监听线程
void MainInterface::initializeNetworkStatusThread()
{
    m_dealNetworkStatus = new DealNetworkStatus;
    m_dealNetworkStatus->moveToThread(&m_dealNetworkStatusThread);
    //设置网络状态
    connect(m_dealNetworkStatus, &DealNetworkStatus::sendNetworkStatus,
            this, [&](int status){
                if(status == NetworkStatus::Normal){//外网正常
                    //qDebug()<<"NetworkStatus::Normal";
                }else if(status == NetworkStatus::Disconnect){//断网
                    emit stopMonitorNetworkStatus();
                    // qDebug()<<"NetworkStatus::Disconnect";

                    auto button = QMessageBox::warning(this,  tr("错误提示"),
                                                       QString("是否已重新连接网络？"),  QString("确定"),  0);
                    if (button == 0) {

                        emit startMonitorNetworkStatus();

                    }
                }
            });


    //是否启动网络状态监听
    connect(this, &MainInterface::startMonitorNetworkStatus,
            m_dealNetworkStatus, &DealNetworkStatus::startMonitorNetwork);

    connect(this, &MainInterface::stopMonitorNetworkStatus,
            m_dealNetworkStatus, &DealNetworkStatus::stopMonitorNetwork);

    connect(&m_dealNetworkStatusThread, &QThread::finished,
            this, &DealNetworkStatus::deleteLater);

    //设置线程优先级
    /*
    QThread::InheritPriority (给创建的线程赋予目前线程同样的等级（默认情况下就为这个）) ,
    QThread::TimeCriticalPriority (尽可能频繁的调度),
     QThread::HighestPriority  >  QThread::HighPriority >  QThread::NormalPriority(操作系统默认的优先级)
    > QThread::LowPriority > QThread::LowestPriority  >QThread::IdlePriority (没有其他线程运行的时候才进行调度)
      */
    // m_dealNetworkStatusThread.setPriority(QThread::InheritPriority);
    m_dealNetworkStatusThread.start();

    emit startMonitorNetworkStatus();
}
//获得全部ip
QStringList MainInterface::getLocalIPs()
{
    QStringList ips;
#ifdef emsdk
    ips << "127.0.0.1";
#else
    QList<QNetworkInterface> netInterfaces = QNetworkInterface::allInterfaces();
    foreach (const QNetworkInterface  &netInterface, netInterfaces) {
        //移除虚拟机和抓包工具的虚拟网卡
        QString humanReadableName = netInterface.humanReadableName().toLower();
        if (humanReadableName.startsWith("vmware network adapter") || humanReadableName.startsWith("npcap loopback adapter")) {
            continue;
        }

        //过滤当前网络接口
        bool flag = (netInterface.flags() == (QNetworkInterface::IsUp | QNetworkInterface::IsRunning | QNetworkInterface::CanBroadcast | QNetworkInterface::CanMulticast));
        if (flag) {
            QList<QNetworkAddressEntry> addrs = netInterface.addressEntries();
            foreach (QNetworkAddressEntry addr, addrs) {
                //只取出IPV4的地址
                if (addr.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                    QString ip4 = addr.ip().toString();
                    if (ip4 != "127.0.0.1") {
                        ips.append(ip4);
                    }
                }
            }
        }
    }
#endif
    return ips;
}
//获得单独的ip
QString MainInterface::getLocalIP()
{
    //优先取192开头的IP,如果获取不到IP则取127.0.0.1
    QString ip = "127.0.0.1";
    QStringList ips = getLocalIPs();
    foreach (QString str, ips) {
        if (str.startsWith("192.168.1") || str.startsWith("192")) {
            ip = str;
            break;
        }
    }
    return ip;
}

